package com.framework.bdf4j.msg.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.msg.constant.PublicConstant;
import com.framework.bdf4j.msg.entity.domain.SysMessages;
import com.framework.bdf4j.msg.entity.dto.SysMessagesQueryDTO;
import com.framework.bdf4j.msg.entity.dto.SysMessagesSaveDTO;
import com.framework.bdf4j.msg.entity.dto.SysMessagesUpdateDTO;
import com.framework.bdf4j.msg.entity.vo.SysMessagesVo;
import com.framework.bdf4j.msg.service.SysMessagesService;
import com.framework.bdf4j.msg.service.SysMsgReceiverService;
import com.framework.bdf4j.msg.service.SysMsgResultService;
import com.framework.bdf4j.sysadm.entity.SysDept;
import com.framework.bdf4j.sysadm.service.SysDeptService;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 消息基础表
 *
 * @author shan.deng
 * @date 2020-07-19 22:24:48
 */
@Controller
@AllArgsConstructor
@RequestMapping("/msg/messages" )
@Api(value = "messages", tags = "消息基础表管理")
public class MessagesController {

    private final SysMessagesService messagesService;

    private final SysMsgReceiverService sysMsgReceiverService;

    private final SysMsgResultService sysMsgResultService;

    private final SysDeptService sysDeptService;

    private static String prefix = "msg/messages";

    @GetMapping("/index")
    public String goList() {
        return prefix + "/messagesList";
    }

    @GetMapping("/selectDept")
    public String selectDept(@RequestParam(required = false) String deptId, ModelMap mmap) {
        SysDept dept = new SysDept();
        if (StringUtils.isNotEmpty(deptId)) {
            dept = sysDeptService.getById(deptId);
        }
        mmap.put("dept", dept);
        return prefix + "/deptTree";
    }

    @GetMapping("/selectRole")
    public String selectRole() {
        return prefix + "/roleTable";
    }

    @GetMapping("/selectUser")
    public String selectUser() {
        return prefix + "/userTable";
    }

    /**
     * 跳转到消息基础编辑页
     */
    @GetMapping("/goEditPage")
    public String goEditPage(@RequestParam(required = false) String id, @RequestParam String oper, Model model) {
        SysMessagesVo sysMessages = new SysMessagesVo();
        if (!"add".equals(oper)) {
            sysMessages = messagesService.getMessagesById(Integer.parseInt(id));
        }
        model.addAttribute("viewobject", sysMessages);
        model.addAttribute("oper", oper);
        return prefix + "/messagesEdit";
    }

    /**
     * 跳转到消息基础编辑页
     */
    @GetMapping("/goMessageMyList")
    public String goMessageMyList() {
        return prefix + "/messagesMyList";
    }

    /**
     * 跳转到消息基础编辑页
     */
    @GetMapping("/goMessageResult/{msgId}")
    public String goMessageResult(@PathVariable(value="msgId") String msgId) {
        return prefix + "/messagesResult";
    }


    /**
     * 分页查询自己收到的消息
     * @param page
     * @param sysMessagesQueryDTO
     * @return
     */
    @ApiOperation(value = "分页查询自己收到的消息", notes = "分页查询自己收到的消息",response = SysMessagesVo.class )
    @GetMapping("/page/received" )
    @ResponseBody
    public R getMessagesPageMyReceived(Page page, SysMessagesQueryDTO sysMessagesQueryDTO) {
        return R.ok(messagesService.pageMessageMyReceived(page, sysMessagesQueryDTO));
    }

    /**
     * 分页查询自己发送的消息
     * @param page 分页对象
     * @param sysMessagesQueryDto 消息基础表
     * @return
     */
    @ApiOperation(value = "分页查询自己发送的消息", notes = "分页查询自己发送的消息" ,response = SysMessagesVo.class )
    @GetMapping("/page" )
    @ResponseBody
    public R getMessagesPageMySend(Page page, SysMessagesQueryDTO sysMessagesQueryDto) {
        IPage<SysMessagesVo> sysMessagesVoIPage = messagesService.pageMessageMySend(page, sysMessagesQueryDto);
        sysMessagesVoIPage.getRecords().stream().forEach(sysMessagesVo -> {
            String sendChannel = sysMessagesVo.getSendChannel();
            List<String> list = Splitter.on(",").trimResults().splitToList(sendChannel);
            sysMessagesVo.setSendChannels(list);
        });
        return R.ok(sysMessagesVoIPage);
    }

    @ApiOperation(value = "获取未读消息数量", notes = "获取未读消息数量")
    @GetMapping("/count" )
    @ResponseBody
    public R getNotReadMessageCount() {
        return R.ok(sysMsgReceiverService.countNotReadMessage());
    }


    @ApiOperation(value = "根据Id将消息置为已读", notes = "根据Id将消息置为已读")
    @PutMapping("/read/{msgId}" )
    @ResponseBody
    public R readMessage(@PathVariable("msgId") Integer msgId) {

        return R.ok(sysMsgReceiverService.readMessageById(msgId));
    }

    /**
     * 通过id查询消息基础表
     * @param msgId id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询",response = SysMessagesVo.class)
    @GetMapping("/{msgId}" )
    @ResponseBody
    public R getById(Page page, @PathVariable("msgId" ) Integer msgId) {
        return R.ok(sysMsgResultService.getMessagesById(page, msgId));
    }

    /**
     * 通过id查询消息(收到的)
     * @param msgId id
     * @return R
     */
    @ApiOperation(value = "通过id查询收到的消息", notes = "通过id查询收到的消息",response = SysMessagesVo.class)
    @GetMapping("/received/{msgId}" )
    @ResponseBody
    public R getReceivedById(@PathVariable("msgId" ) Integer msgId) {
        return R.ok(messagesService.getReceivedMessagesById(msgId));
    }

    /**
     * 新增消息基础表
     * @param sysMessagesSaveDTO 消息基础表
     * @return R
     */
    @ApiOperation(value = "新增消息基础表", notes = "新增消息基础表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('msg_add')" )
    @ResponseBody
    public R save(@RequestBody SysMessagesSaveDTO sysMessagesSaveDTO) {
        return R.ok(messagesService.saveMessages(sysMessagesSaveDTO));
    }

    /**
     * 修改消息基础表
     * @param sysMessagesUpdateDTO 消息基础表
     * @return R
     */
    @ApiOperation(value = "修改消息基础表", notes = "修改消息基础表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('msg_edit')" )
    @ResponseBody
    public R updateById(@RequestBody SysMessagesUpdateDTO sysMessagesUpdateDTO) {
        if(sysMessagesUpdateDTO.getMsgId() == null) {
            return R.failed("必须要填写Id");
        }
        SysMessages sysMessages = messagesService.getById(sysMessagesUpdateDTO.getMsgId());
        if(PublicConstant.MSG_STATUS_SEND.equals(sysMessages.getMsgStatus())) {
            return R.failed("该消息已被发送,不能编辑");
        }
        return R.ok(messagesService.updateMessages(sysMessagesUpdateDTO));
    }

    /**
     * 通过id删除消息基础表
     * @param msgId id
     * @return R
     */
    @ApiOperation(value = "通过id删除消息基础表", notes = "通过id删除消息基础表")
    @DeleteMapping("/{msgId}" )
    @PreAuthorize("@pms.hasPermission('msg_del')" )
    @ResponseBody
    public R removeById(@PathVariable Integer msgId) {

        SysMessages sysMessages = messagesService.getById(msgId);

        if(sysMessages == null) {
            return R.failed("不能删除不存在的消息");
        }

        if(PublicConstant.MSG_STATUS_SEND.equals(sysMessages.getMsgStatus())) {
            return R.failed("该消息已被发送,不能删除");
        }
        return R.ok(messagesService.deleteMessages(msgId));
    }

    /**
     * 发送消息
     * @param msgId id
     * @return R
     */
    @ApiOperation(value = "通过id发送消息", notes = "通过id发送消息")
    @PutMapping("/send/{msgId}" )
    @ResponseBody
    public R sendMessage(@PathVariable Integer msgId) {

        SysMessagesVo messages = messagesService.getMessagesById(msgId);

        if(PublicConstant.MSG_STATUS_SEND.equals(messages.getMsgStatus())) {
            return R.failed("该消息已被发送,不能多次发送");
        }
        return R.ok(messagesService.sendMessage(messages));
    }
}
